package com.yn.courseselectionsystem.controller;

import com.yn.courseselectionsystem.pojo.ChatHistory;
import com.yn.courseselectionsystem.server.ChatSocketServer;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: TODO
 * @author: Tokyo_God
 * @date: 2021/2/10 12:01
 * Role of:
 * @version: v1.0
 */
//@SessionAttributes(value = {"chatMsgs"})
@Controller
public class ChatHistoryController {
    /*@Resource
    private ChatSocketServer chatSocketServer;*/

    /**
     * 获取在线人数
     * @return
     */
    @GetMapping("/studentManagement/succPage/chatHistoryController/geTonLineUserNames")
    @ResponseBody
    public List<String> geTonLineUserNames(){
        List<String> usernames=new ArrayList<>();
        for (String str:ChatSocketServer.getSessionPool().keySet()){
            usernames.add(str);
        }
        return usernames;
    }

    /**
     * 将聊天记录保存到  作用域
     * @param chatHistory
     * @param model
     * @return
     */
    @GetMapping("/studentManagement/succPage/chatHistoryController/conserveMsg")
    @ResponseBody
    public Integer conserveMsg(ChatHistory chatHistory, Model model, HttpSession session){
        ServletContext application=session.getServletContext();
        List<ChatHistory> chatHistoryList;
        if (application.getAttribute("chatMsgs")==null){
            chatHistoryList=new ArrayList<ChatHistory>();
//            model.addAttribute("chatMsgs",chatHistoryList);
            application.setAttribute("chatMsgs",chatHistoryList);
        }else{
            chatHistoryList= ((List<ChatHistory>) application.getAttribute("chatMsgs"));
        }
        chatHistoryList.add(chatHistory);
        return 1;
    }

    /**
     * 获取所有的聊天记录
     * @param session
     * @return
     */
    @GetMapping("/studentManagement/succPage/chatHistoryController/getChat")
    @ResponseBody
    public List<ChatHistory> getChat(HttpSession session){
        ServletContext application=session.getServletContext();
        return ((List<ChatHistory>) application.getAttribute("chatMsgs"));
    }

}
